import React, { useState,useEffect,useRef } from 'react';
import { Table, Button, Modal, Space, message  } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { EditOutlined, DeleteOutlined, EyeOutlined,ProfileFilled,AppstoreAddOutlined,LinkOutlined } from '@ant-design/icons';
import UploadAttachment from '../../../components/upload/UploadAttachment';
import PermissionManage from './PermissionManage'
import DirectoryAddForm from './DirectoryAddForm'
import DirectoryEditForm from './DirectoryEditForm'
import DirectoryViewForm from './DirectoryViewForm'
import DirectoryDocumentList from './DirectoryDocumentList'
import { getDirectoryInfoList,deleteDirectoryInfoRecord,getDirectoryInfoNormalList } from '../../../apis/backhub/directory';


interface Directory {
  id: number;
  name: string;
  parentId:number;
  directoryPath:string;
  createDateTime?:string;
  children?:Directory[]
}

interface BaseTree {
  title: string;
  value:string;
  children?:BaseTree[]
}

const DirectoryManager: React.FC = () => {
	const [directories, setDirectories] = useState<Directory[]>([]);
	const [dirDatas, setDirDatas] = useState<Directory[]>([]);
	const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
	const [viewModalVisible, setViewModalVisible] = useState<boolean>(false);
	const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
	const [documentVisible, setDocumentVisible] = useState<boolean>(false);
	const [permissionVisible, setPermissionVisible] = useState<boolean>(false);
	const [directoryId, setDirectoryId] = useState<number>(0);
	const [directoryName, setDirectoryName] = useState<string>('');
	
	useEffect(() => {
	  fetchData();
	}, []);
	
	const fetchData = async() => {
		const res = await getDirectoryInfoList({parentId:0})
		if(res.status){
			setDirectories(res.data.page)
		}
		const resp = await getDirectoryInfoNormalList({parentId:0})
		if(resp.status){
			setDirDatas(resp.data.page)
		}
	};
	
	const handleAddDirectory = () => {
		setIsModalVisible(true);
	};

	const handleCancel = () => {
		setIsModalVisible(false);
	};
	
	const handleViewCancel=()=>{
		setViewModalVisible(false)
	}
	
	const handleEditCancel=()=>{
		setEditModalVisible(false)
	}
	let childList = useRef(null);
	const handleDocument=(record: Directory)=>{
		setDirectoryId(record.id);
		setDirectoryName(record.name);
		setDocumentVisible(true);
		if(childList.current){
			setTimeout(function(){
				childList.current?.func();
			},100)
		}
	}
	
	const handleDocumentCancel=()=>{
		setDocumentVisible(false)
	}
	
	const handlePermissionCancel=()=>{
		setPermissionVisible(false)
	}

	const onAddSuccess=()=>{
		setIsModalVisible(false);
		fetchData();
	}
	const childView = useRef(null)
	const handleView = (record: Directory) => {
		setDirectoryId(record.id);
		setDirectoryName(record.name);
		setViewModalVisible(true);
		if(childView.current){
			setTimeout(function(){
				childView.current?.func();
			},100)
		}
	};
	const childEdit = useRef(null)
	const handleEdit = (record: Directory) => {
		setDirectoryId(record.id);
		setDirectoryName(record.name);
		setEditModalVisible(true);
		if(childEdit.current){
			setTimeout(function(){
				childEdit.current?.func();
			},100)
		}
	};
	const onEditSuccess=()=>{
		setEditModalVisible(false);
		fetchData();
	}
	
	const handleDelete = (record: Directory) => {
		Modal.confirm({
		title: '确认删除',
		content: `确定要删除 ${record.name} 目录吗？`,
		okText:"确认",
		cancelText:"取消",
		onOk: async() => {
			const res = await deleteDirectoryInfoRecord({ids:record.id.toString()})
			if(res.status&&res.data.success){
				message.success('删除成功');
				fetchData();
			}
		},
		});
	};
	const permissionChild = useRef(null);
	const handlePermission=(record: Directory)=>{
		setDirectoryId(record.id);
		setDirectoryName(record.name);
		setPermissionVisible(true)
		setTimeout(function(){
			permissionChild.current?.func()
		},100)
	}
	const columns: ColumnsType<Directory> = [
		{
		  title: '目录名称',
		  dataIndex: 'name',
		  width: '25%',
		  key: 'name',
		},
		{
		  title: '上级目录',
		  dataIndex: 'parentId',
		  width: '25%',
		  key: 'parentId',
		  render: (parentId: number) => {
		  	const parent = dirDatas.find(dir => dir.id === parentId);
		  	return parent ? parent.name : '根目录';
		  }
		},
		{
		  title: '创建时间',
		  dataIndex: 'createDateTime',
		  width: '15%',
		  key: 'createDateTime',
		  render: (date: string) => new Date(date).toLocaleString(),//格式化时间
		},
		{
		  title: '操作',
		  key: 'action',
		  render: (_: any, record: Directory) => (
		    <Space size="middle">
		      <Button
		        type="link"
		        icon={<EyeOutlined />}
		        onClick={() => handleView(record)}
		      >
		        查看
		      </Button>
		      <Button
		        type="link"
		        icon={<EditOutlined />}
		        onClick={() => handleEdit(record)}
		      >
		        编辑
		      </Button>
		      {
				  (record.parentId.toString()!=="0"&&record.id.toString()!=="312810899759042560"&&record.id.toString()!=="312810987713597440")&&<Button
					type="link"
					danger
					icon={<DeleteOutlined />}
					onClick={() => handleDelete(record)}
				  >
					删除
				  </Button>
			  }
			  <Button
			    type="link"
			    icon={<ProfileFilled />}
			    onClick={() => handleDocument(record)}
			  >
			    查看文件
			  </Button>
			  <Button
			    type="link"
			    icon={<AppstoreAddOutlined />}
			    onClick={() => handlePermission(record)}
			  >
			    权限管理
			  </Button>
		    </Space>
		  ),
		},
	];
	
	const handleUploadSuccess = (file: any) => {
	    console.log('文件上传成功:', file);
	    // 这里可以进行进一步处理，如显示上传的文件信息等
	};
	
	const customDealRequest = (file: any) => {
	    console.log('文件上传处理:', file);
	    // 这里可以进行进一步处理，如显示上传的文件信息等
	};
	// <UploadAttachment
	// 	directory={307342944220876800}
	// 	maxFileSize={5 * 1024 * 1024} // 限制文件大小为 5MB
	// 	onUploadSuccess={handleUploadSuccess}
	// 	customDealRequest={customDealRequest}
	// 	accept={".pdf"}
	// 	child={<LinkOutlined />}
	// />
	const locale = {
		emptyText:'暂无数据',
	}
	return (
		<div>
		  <Button type="primary" onClick={handleAddDirectory}>
			添加目录
		  </Button>
		  <Table dataSource={directories} locale={locale} columns={columns} rowKey="id" />
		  <Modal
			title="添加目录"
			visible={isModalVisible}
			onCancel={handleCancel}
			footer={null}
		  >
			<DirectoryAddForm  onSuccess={onAddSuccess} />
		  </Modal>
		  <Modal
				title="编辑目录"
				visible={editModalVisible}
				onCancel={handleEditCancel}
				footer={null}
			>
				<DirectoryEditForm ref={childEdit} directoryId={directoryId} onSuccess={onEditSuccess}/>
		  </Modal>
		  <Modal
				title="目录查看"
				visible={viewModalVisible}
				onCancel={handleViewCancel}
				footer={null}
			>
				<DirectoryViewForm ref={childView}  directoryId={directoryId} />
		  </Modal>
		  <Modal
				title="目录附件"
				visible={documentVisible}
				onCancel={handleDocumentCancel}
				width={1000}
				footer={null}
			>
				<DirectoryDocumentList ref={childList}  directoryId={directoryId} />
		  </Modal>
		  
		  <Modal
				title="权限管理"
				visible={permissionVisible}
				onCancel={handlePermissionCancel}
				width={1000}
				footer={null}
			>
				<PermissionManage ref={permissionChild} directory={directoryId} directoryName={directoryName}/>
		  </Modal>
		</div>
	);
};

export default DirectoryManager;
